package net.cl7.controller;

import net.cl7.model.Item;
import net.cl7.util.CommonResult;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;


@RestController
@RequestMapping("api/vue_learn/")
@CrossOrigin
public class VueLearnController {
    private List<Item> itemList = new ArrayList<>();

    public VueLearnController(){
        itemList.add(new Item(this.itemList.size() + 1, "宝马", new Date()));
        itemList.add(new Item(this.itemList.size() + 1, "奔驰", new Date()));
    }

    @GetMapping("item_list")
    @ResponseBody
    public CommonResult itemList(){
        return CommonResult.ok().setResult(itemList);
    }

    @PostMapping("add_item")
    @ResponseBody
    public CommonResult addItem(@RequestBody Item item){
        item.setId(this.itemList.size() + 1);
        item.setTime(new Date());
        itemList.add(item);
        return CommonResult.ok().setResult(itemList);
    }

    @GetMapping("del_item/{itemId}")
    public CommonResult delItem(@PathVariable("itemId") Integer itemId){
        Iterator<Item> iterator = itemList.iterator();
        while (iterator.hasNext()){
            Item item = iterator.next();
            if(item.getId().equals(itemId)){
                iterator.remove();
                break;
            }
        }
        return CommonResult.ok().setResult(itemList);
    }
}
